import asyncio
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from pyrogram.types.messages_and_media import Message
from app.models.async_test import Users, TgBot


class AsyncUser:
    def __init__(self, message: Message, session: AsyncSession) -> None:
        self.message = message
        self.session = session

    async def _async_init(self):
        tgbot = (
            await self.session.execute(
                select(TgBot).filter(TgBot.name == self.message.from_user.first_name)
            )
        ).scalar_one_or_none()

        if not tgbot:
            tgbot = TgBot(name=self.message.from_user.first_name)
            user = Users(name=self.message.from_user.first_name, amount=0, tgbot=tgbot)
            self.session.add(user)
        self.tgbot = tgbot
        self.user = tgbot.user

    async def __aenter__(self):
        await self._async_init()
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        pass
